Java Beans - 2025
JavaBeans are a standard way to create reusable Java components. They are simply Java classes that follow a specific set of rules.
What Is a JavaBean?A JavaBean is a simple Java class that:
package com.example;
import java.io.Serializable;
public class Worker implements Serializable {
private String name;
private int age;
// 1. No-arg constructor
public Worker() {}
// 2. Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Worker p = new Worker(); // Create bean object
// Set values
p.setName("Dinesh");
p.setAge(30);
// Get values
System.out.println("Name: " + p.getName());
System.out.println("Age: " + p.getAge());
}
}
<jsp:useBean id="person" class="Person" scope="session" />
<jsp:setProperty name="person" property="name" value="Dinesh"/> <jsp:setProperty name="person" property="age" value="25"/>
Name: <jsp:getProperty name="person" property="name"/> Age: <jsp:getProperty name="person" property="age"/>
Using JavaBeans inside a web application (WEB folder) with WEB-INF is a very common pattern in JSP/Servlet projects. Below is a clear, step-by-step guide showing exact folder structure, where to put the bean, and how to use it in JSP.
| myapps (Folder) | |||||
| beanform.html (file) | |||||
| beanresult.jsp (file) | |||||
| WEB-INF (Folder) | |||||
| web.xml | |||||
| classes (Folder) | |||||
| com (Folder) | |||||
| example (Folder) | |||||
| Worker.java (file inside example folder) | |||||
| Worker.class (file inside example folder) | |||||
In JSP, when you use JavaBeans with <jsp:useBean>, you can place the bean in different scopes. These scopes control how long the bean lives, who can access it, and when it gets destroyed.
| Scope | Lifetime | Accessible By | Where Stored |
|---|---|---|---|
| page | For the current JSP page only | Only that JSP | PageContext |
| request | For a single HTTP request | All JSP/Servlets in same request | HttpServletRequest |
| session | Until the user session ends | Same user across pages | HttpSession |
| application | Entire web app lifecycle | All users, all pages | ServletContext |
<form action="beanresult.jsp">
Name: <input type="text" name="name">
Age: <input type="text" name="age">
<input type="submit" value="Submit">
</form>
<jsp:useBean id="p" class="com.example.Worker" scope="session" /> <jsp:setProperty name="p" property="name" param="name"/> <jsp:setProperty name="p" property="age" param="age"/>
Name: <jsp:getProperty name="p" property="name"/> Age: <jsp:getProperty name="p" property="age"/>